<template>
  <div class="app-container">
    <el-card class="box-card">
      <el-form :inline="true" :model="listQuery" size="small">
        <el-form-item label="">
          <el-input
            style="min-width: 230px"
            v-model="listQuery.name"
            placeholder="输入商品编号/名称/助记码"
            clearable
            @keyup.enter.native="handleFilter"
          >
          </el-input>
        </el-form-item>
        <el-form-item label="">
          <el-select v-model="listQuery.house" placeholder="仓库" clearable>
            <el-option
              v-for="item in houses"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            size="mini"
            icon="el-icon-search"
            @click.native="handleFilter"
            >查询</el-button
          >
        </el-form-item>
        <el-form-item label="">
          <el-button
            type="success"
            icon="el-icon-download"
            size="mini"
            @click.native="handleExport"
            >导出</el-button
          >
        </el-form-item>
      </el-form>
      <el-container>
        <el-aside width="218px">
          <el-tree
            :data="categories"
            :props="defaultProps"
            @node-click="handleNodeClick"
            default-expand-all
            :expand-on-click-node="false"
            node-key="id"
          ></el-tree>
        </el-aside>
        <el-main>
          <el-table
            :data="datas"
            border
            v-loading="listLoading"
            fit
            highlight-current-row
            style="width: 100%"
            size="small"
            @selection-change="handleSelectionChange"
            show-summary
            :summary-method="getSummaries"
          >
            <el-table-column type="selection" align="center" />
            <el-table-column
              v-for="column in tableColumns"
              :key="column.key"
              :label="column.title"
              :prop="column.key"
              :align="column.align"
              :width="column.width ? column.width : ''"
              :formatter="dataFormatter"
            >
            </el-table-column>
          </el-table>
          <!-- 分页 -->
          <pagination
            v-show="total > 0"
            :total="total"
            :page.sync="listQuery.page"
            :limit.sync="listQuery.page_size"
            @pagination="getGoodsStockList"
          />
        </el-main>
      </el-container>
    </el-card>
    <el-dialog title="正在下载，请等待" :visible.sync="progressShow" :close-on-click-modal="false" :close-on-press-escape="false" :show-close="false" width="20%">
            <div style="text-align: center;">
                <el-progress :percentage="percentage" type="circle"></el-progress>
            </div>
        </el-dialog>
  </div>
</template>

<script>
import Pagination from "@/components/Pagination";
import { getParentsPath } from "@/utils/index";
import { getCategories } from "@/api/base";
import {
  getGoodsStocks,
  deleteGoodsStocks,
  exportStockGoods,
} from "@/api/store";
import { getHouseList } from "@/api/base";

export default {
  name: "GoodsStock",
  data() {
    return {
      tableColumns: [
        {
          key: "goods_code",
          title: "商品编号",
          width: "120",
        },
        {
          key: "goods_name",
          title: "商品名称",
          width: "200",
        },
        {
          key: "goods_cate_name",
          title: "商品分类",
          width: "120",
        },
        {
          key: "house_name",
          title: "所属仓库",
          width: "120",
        },
        {
          key: "goods_unit_name",
          title: "计量单位",
          width: "80",
          align: "center",
        },

        {
          key: "quantity",
          title: "库存数量",
          width: "120",
        },
        {
          key: "price",
          title: "成本单价",
          width: "100",
        },
        {
          key: "total_amount",
          title: "成本总价",
          width: "100",
        },
        {
          key: "specs",
          title: "规格",
          width: "120",
        },
        {
          key: "brand",
          title: "品牌",
          width: "100",
        },
        {
          key: "place",
          title: "产地",
          width: "120",
        },
        {
          key: "help_code",
          title: "助记码",
        },
        {
          key: "bar_code",
          title: "条码",
        },
        {
          key: "supplier_name",
          title: "供应商",
          width: "120",
        },
        {
          key: "remark",
          title: "备注",
          width: "180",
        },
      ],

      title: "库存商品",

      datas: [],
      categories: [],
      cates: [],
      houses: [],
      percentage: 0,
      progressShow: false,

      selectedKeys: [],
      selections: [],

      total: 0,
      listLoading: true,
      listQuery: {
        page: 1,
        page_size: 15,
        name: "",
        parent_id: null,
        cate_id: null,
        house: null,
      },
      //cascader
      props: {
        expandTrigger: "hover",
        value: "id",
        label: "name",
        children: "children",
      },
      //tree
      defaultProps: {
        children: "children",
        label: "name",
      },
    };
  },
  computed: {
    getTitle() {
      return this.dialogType == "new"
        ? `新增${this.title}`
        : `编辑${this.title}`;
    },
  },
  components: {
    Pagination,
  },
  created() {
    this.getCategoryList();
    this.getGoodsStockList();
    this.getStoreHouseList();
  },
  methods: {
    getCategoryList() {
      getCategories().then((res) => {
        console.log(res);
        this.cates = res;
        this.categories.push({ id: -1, name: "商品分类", children: res });
      });
    },
    getGoodsStockList() {
      this.listLoading = true;
      getGoodsStocks(this.listQuery)
        .then((res) => {
          this.datas = res.results;
          this.listLoading = false;
          this.total = res.count;
        })
        .catch((error) => {
          this.$message.error("获取数据失败!" + error);
          this.listLoading = false;
        });
    },

    getStoreHouseList() {
      getHouseList().then((res) => {
        this.houses = res;
      });
    },

    handleExport() {
      this.progressShow = true
      this.percentage = 0;
      exportStockGoods(this.listQuery, (progressEvent) => {
        //progressEvent.loaded 下载文件的当前大小
        //progressEvent.total  下载文件的总大小
        // console.log(progressEvent)
        let progressBar = Math.round(
          (progressEvent.loaded / progressEvent.total) * 100
        );
        //接收进度为99%的时候需要留一点前端编译的时间
        if (progressBar >= 99) {
          this.percentage = 99;
          this.$message.success("下载完成。");

        } else {
          this.percentage = progressBar;
          // this.$message("正在下载，请稍等。");
        }
        
      })
        .then((res) => {
          // console.log(res);
          if (res.data.type === "application/octet-stream") {
            let filename = res.headers["content-disposition"];
            const blob = new Blob([res.data]);
            let downloadElement = document.createElement("a");
            var href = window.URL.createObjectURL(blob); //创建下载的链接
            downloadElement.href = href;
            downloadElement.download = decodeURI(
              filename.split("filename=")[1]
            ); //下载后文件名

            document.body.appendChild(downloadElement);
            downloadElement.click(); //点击下载
            document.body.removeChild(downloadElement); //下载完成移除元素
            window.URL.revokeObjectURL(href); //释放掉blob对象
            this.progressShow = false;
            this.percentage =0;
          }
        })
        .catch((error) => {
          this.$message.error("获取数据失败:" + error);
          this.progressShow = false;
          this.percentage = 0;
        });
    },

    //树形点击
    handleNodeClick(data) {
      if (data.children) {
        // 父类
        this.listQuery.parent_id = data.id;
        this.listQuery.cate_id = null;
      } else {
        this.listQuery.parent_id = null;
        this.listQuery.cate_id = data.id;
      }

      this.handleFilter();
    },

    handleChange(value) {
      console.log(value);
      if (this.selectedKeys.length > 0) {
        this.form.cate = this.selectedKeys[this.selectedKeys.length - 1];
      }
    },

    // 查询
    handleFilter() {
      this.listQuery.page = 1;
      this.getGoodsStockList();
    },

    handleSelectionChange(val) {
      this.selections = val.map((item) => item.id);
    },

    dataFormatter(row, column, cellValue, index) {
      if (
        column.property === "total_amount" ||
        column.property === "quantity" ||
        column.property === "price"
      ) {
        cellValue = cellValue || 0;
        return (
          (cellValue || cellValue === 0) && parseFloat(cellValue).toFixed(2)
        );
      } else {
        return cellValue;
      }
    },

    getSummaries(param) {
      const { columns, data } = param;
      const sums = [];
      columns.forEach((column, index) => {
        if (index === 2) {
          sums[index] = "合计";
          return;
        }
        if (
          column.property === "total_amount" ||
          column.property === "quantity"
        ) {
          const values = data.map((item) => item[column.property]);
          sums[index] = values
            .reduce((prev, curr) => {
              return prev + curr;
            }, 0)
            .toFixed(2);
          sums[index] += column.property === "quantity" ? "" : " 元";
        } else {
          return;
        }
      });
      return sums;
    },

    //批量删除
    // handleBatchDelete() {
    //   if (this.selections.length == 0) {
    //     this.$message.warning("请选择要删除记录");
    //     return;
    //   }
    //   this.$confirm("确定要删除选中记录吗?", "删除提示：", {
    //     confirmButtonText: "确定",
    //     cancelButtonText: "取消",
    //     type: "warning",
    //   })
    //     .then(async () => {
    //       const sel_ids = {
    //         select_ids: this.selections,
    //       };
    //       const res = await delMultiGoods(sel_ids);
    //       this.getGoodsList();
    //       this.$message({
    //         type: "success",
    //         message: "删除成功!",
    //       });
    //     })
    //     .catch((err) => {
    //       this.$message({
    //         type: "success",
    //         message: "删除失败!" + err,
    //       });
    //     });
    // },
  },
};
</script>

<style lang='scss' scoped>
.el-aside {
  .el-tree {
    border: 1px solid #eee;
    padding: 10px;
  }
}
.el-cascader,
.el-select {
  width: 100%;
}
.el-link {
  font-size: 12px;
}
</style>